<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Tools {
    private $CI;

    public function __construct()
    {
        $this->CI = &get_instance();
    }

    public function initFoldersBatch()
    {
        $this->CI->load->model('entity/user_entity', 'User_Entity');
        $this->CI->db->select('id, role');
        $this->CI->db->from($this->CI->db->dbprefix('user'));
        $aUsers = $this->CI->db->get()->result();
        $aFolders = array();
        foreach ($aUsers as $u) {
            $image_folder = random_string('alnum', 18);
            while (file_exists(FCPATH . UPLOAD_FOLDER_URL . $image_folder)) {
                $image_folder = random_string('alnum', 18);
            }
            $aFolders[] = array('folder' => $image_folder, 'role' => $u->role);
            $u->image_folder = $image_folder;
        }
        $this->CI->db->trans_begin();
        $this->CI->db->update_batch($this->CI->db->dbprefix('user'), $aUsers, 'id');
        if ($this->CI->db->trans_status() === false) {
            $this->CI->db->trans_rollback();
        } else {
            $result = true;
            foreach ($aFolders as $f) {
                $path = FCPATH . UPLOAD_FOLDER_URL . 'public/' . $f['folder'];
                if (!mkdir($path, 0777, true)) {
                    $result = false;
                    break;
                } else {
                    $result = $this->initFolder($path, $f['role']);
                    if (!$result) {
                        break;
                    }
                }
            }
            if ($result) {
                $this->CI->db->trans_commit();
            } else {
                foreach ($aFolders as $f) {
                    $path = FCPATH . UPLOAD_FOLDER_URL . 'public/' . $f['folder'];
                    if (file_exists($path)) {
                        rmdir($path);
                    }
                }
                $this->CI->db->trans_rollback();
            }
        }
    }

    public function initFolder($path, $role)
    {
        $result = true;
        $aFolder = unserialize(UPLOAD_STRUCT);

        $folder = $aFolder[$role];
        foreach ($folder as $f) {
            if (!mkdir($path . '/' . $f, 0777, true)) {
                $result = false;
                break;
            } else {
                touch($path . '/role-' . $role . '.html');
            }
        }
        return $result;
    }
}
?>